<template>
	<uv-form labelPosition="left" :model="model" :rules="rules" ref="form">
		<template v-for="[key, field] in Object.entries(options)" :key="key">
			<view class="borderbottom" v-if="field.isShow != 1">
				<uv-form-item :label="field.title" :prop="'userInfo.' + key" label-width="120" labelPosition="left" labelAlign="center">
					<!-- 动态渲染表单项 -->
					<template v-if="field.type === 'input'">
						<uv-input v-model="model[key]" :placeholder="field.placeholder" :disabled="readonly || field.disabled" border="none" />
					</template>
					<template v-if="field.type === 'upload'">
						<uploadView :tips="field.placeholder" :maxCount="readonly ? 0 : field.maxCount" :customUrl="field.customUrl" :readonly="readonly" v-model="model[key]" />
					</template>
					<template v-if="field.type === 'radio'">
						<uv-radio-group v-model="model[key]" :disabled="readonly || field.disabled">
							<uv-radio
								iconColor="#fff"
								activeColor="#fb5f46"
								v-for="option in field.option"
								:key="option.value"
								:label="option.label"
								:name="option.value"
								class="mar10"
							></uv-radio>
						</uv-radio-group>
					</template>
					<template v-if="field.type === 'checkbox'">
						<uv-checkbox-group v-model="model[key]" :disabled="readonly">
							<uv-checkbox
								class="mar10"
								activeColor="#fb5f46"
								iconColor="#fff"
								v-for="(item, index) in field.option"
								:key="index"
								:label="item.label"
								:name="item.value"
							></uv-checkbox>
						</uv-checkbox-group>
					</template>

					<!-- 高级表单交互 -->
					<!-- 弹出复选框 -->
					<template v-if="field.type === 'poupCheckbox'">
						<poupPick :title="'请选择' + field.title">
							<template v-slot:content>
								<scrollYCheckbox :list="field.option" v-model="model[key]" />
							</template>
						</poupPick>
					</template>
					<!-- 弹出身份选择框  商户类型 -->
					<template v-if="field.type === 'poupShopCheckbox'">
						<!-- 		<poupPick :title="'请选择'+field.title">
							<template v-slot:content>
								<view class="pall20 mtb20">
									<shopUserPick v-model="model[key]" />
								</view>
							</template>
						</poupPick> -->
						<view>
							<text @click="openMerchantType" :style="{ color: merchantType ? '#333' : '#999', fontSize: '12rpx' }">
								{{ merchantType ? merchantType : '请选择商户类型' }}
							</text>
						</view>
						<fui-bottom-popup :show="merchantTypeShow" @close="closeMerchantType">
							<view style="padding: 20rpx">
								<view class="cloummStart gap10 w100">
									<view v-for="(item, index) in merchantTypeList" :key="index" class="w100">
										<ListTitle :leftIcon="item.icon" :title="item.name" :desc="item.desc" @click="merchantTypeHandler(item)"></ListTitle>
									</view>
								</view>
							</view>
						</fui-bottom-popup>
					</template>
					<!--期限选择器 -->
					<template v-if="field.type === 'timeRadio'">
						<fui-radio-group @change="timeChageRadio" v-model="model[key]">
							<fui-label class="rowStart gap20">
								<view class="rowStart gap10" v-for="(item, index) in timeRadioItems" :key="index">
									<fui-radio :checked="item.checked" :value="item.value" color="#FF2B2B" borderColor="#B2B2B2"></fui-radio>
									<text class="cardUnit">{{ item.name }}</text>
								</view>
							</fui-label>
						</fui-radio-group>
					</template>
					<!-- 行业类目 -->
					<template v-if="field.type === 'classy'">
						<view class="rowSpaceBetween w100" @click="gotoPage('/pages/tabbar/work/pages/addShopUser/IndustryCategory/IndustryCategory')">
							<view class="cardUnit">
								{{ model[key] == '' ? '请选择' : model[key] }}
							</view>
							<uv-icon name="arrow-right"></uv-icon>
						</view>
					</template>
					<!-- 地区滚动选择器 -->
					<template v-if="field.type === 'area'">
						<view class="rowSpaceBetween w100" @click="selectArea">
							<view class="cardUnit">
								<template v-if="model[key] == ''">
									<view>请选择</view>
								</template>
								<template v-if="model[key] != ''">
									<view v-if="model[key] && typeof model[key] === 'object'" class="rowStart">
										<view v-for="([customKey, customValue], modeIndex) in Object.entries(model[key])" :key="customKey">
											{{ customValue + (modeIndex < Object.entries(model[key]).length - 1 ? '-' : '') }}
										</view>
									</view>
								</template>
							</view>
							<uv-icon name="arrow-right"></uv-icon>
						</view>
						<areaVue ref="areaVue" v-model="model[key]" />
					</template>
					<!-- 地图选择 -->
					<template v-if="field.type === 'map'">
						<view class="map">
							<!-- 暂配测试地图key，正式下来需要更换 -->
							<!-- <mapVue /> -->
						</view>
					</template>
					<!-- 滚动选择器 -->
					<template v-if="field.type === 'scollPicker'">
						<view class="rowSpaceBetween w100" @click="openScollPick">
							<view class="cardUnit">
								{{ model[key] == '' ? '请选择' : model[key] }}
							</view>
							<uv-icon name="arrow-right"></uv-icon>
						</view>
						<scollPickVue ref="scollPickVue" v-model="model[key]" :list="field.option" />
					</template>
					<!-- 银行选择器 -->
					<template v-if="field.type === 'bankCategory'">
						<view class="rowSpaceBetween w100" @click="gotoPage('/pages/tabbar/work/pages/addShopUser/bankBranch/bankBranch')">
							<view class="cardUnit">
								{{ model[key] == '' ? '请选择' : model[key] }}
							</view>
							<uv-icon name="arrow-right"></uv-icon>
						</view>
					</template>
					<template v-if="field.type === 'subBranchType'">
						<uv-radio-group v-model="model[key]" @change="changeSubBranchType">
							<view style="display: flex">
								<uv-radio v-for="(item, index) in field.option" :key="item.value" :label="item.label" :name="item.value"></uv-radio>
							</view>
						</uv-radio-group>
					</template>
					<template v-if="field.type === 'selectP'">
						<uni-data-select :localdata="provinces" @change="changeProvinces"></uni-data-select>
					</template>
					<template v-if="field.type === 'selectC'">
						<uni-data-select :localdata="citys" @change="changeCitys"></uni-data-select>
					</template>
					<template v-if="field.type === 'selectAB'">
						<uni-data-select :localdata="bankList" @change="changeBank"></uni-data-select>
					</template>
				</uv-form-item>
				<!-- 子选项渲染 -->
				<view v-if="field.rateInfo || key == 'rateInfo'">
					<payRateVue ref="payRate" :disabled="readonly" :options="field.rateInfo ?? field" :payRateInfo="model.rateInfo || {}"></payRateVue>
				</view>
				<view v-if="field.subTitle" class="subTitle">
					{{ field.subTitle }}
				</view>
				<template v-if="field.type === 'timeRadio'">
					<dataTimepicker :timeType="model[key]"></dataTimepicker>
				</template>
			</view>
		</template>
	</uv-form>
</template>

<script>
import { areaListApi, bankListApi } from '@/api/store.js';
import uploadView from '@/components/form/uploadView/uploadView.vue';
import payRateVue from './payRate.vue';
import { toRaw } from 'vue';
import poupPick from '@/components/form/poupPick/poupPick.vue';
// import poupCheckbox from '@/components/poupCheckbox/poupCheckbox.vue';
import scrollYCheckbox from '@/components/form/scrollYCheckbox/scrollYCheckbox.vue';
import shopUserPick from '@/pages/tabbar/work/pages/addShopUser/current/shopUserPick.vue';
import dataTimepicker from '@/components/dataTimepicker/dataTimepicker.vue';
import areaVue from '@/components/form/area/area.vue';
import mapVue from '@/components/form/map/map.vue';
import scollPickVue from '@/components/scollPick/scollPick.vue';
import ListTitleVue from '@/components/ListTitle/ListTitle.vue';
export default {
	components: {
		uploadView,
		payRateVue,
		// poupCheckbox,
		scrollYCheckbox,
		shopUserPick,
		dataTimepicker,
		areaVue,
		mapVue,
		scollPickVue,
		poupPick,
		ListTitleVue
	},
	props: {
		options: {
			type: Object,
			required: true
		},
		readonly: {
			type: Boolean,
			default: false
		},
		formInfo: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		return {
			model: {},
			rules: {}, // 基本案列数据
			timeRadioItems: [
				{
					name: '选择时间',
					value: '0',
					checked: false
				},
				{
					name: '长期有效',
					value: '1',
					checked: false
				}
			],
			areasInfo: {
				areaLevel: '',
				cityCd: '',
				cityNm: '',
				mainPass: '1',
				pageNum: 0,
				pageSize: 0,
				parentCityCd: ''
			},
			provinces: [],
			citys: [],
			bankList: [],
			merchantTypeShow: false,
			merchantTypeList: [
				{
					name: '个人商户',
					icon: 'home',
					desc: '需要提供营业执照和法人身份证照片和结算银行卡等'
				},
				{
					name: '企业商户',
					icon: 'empty-permission',
					desc: '一般为有限公司，需要提供营业执照以及法人身份证照片等'
				},
				{
					name: '小微商户',
					icon: 'server-man',
					desc: '无营业执照的商户'
				}
			],
			merchantType: ''
			// rules: this.generateRules(), // 基本案列数据
		};
	},
	computed: {
		// 动态生成表单验证规则
		fields() {
			return this.options;
		}
	},
	mounted() {
		if (!this.formInfo) {
			this.initForm();
		} else {
			this.model = this.formInfo;
		}
		uni.$on('selectIndustry', (e) => {
			this.model['companyCategory'] = e;
		});
		uni.$on('bankBranch', (e) => {
			this.model['bankBranch'] = e;
		});
		// this.rules = this.generateRules();
		this.getProvinceList();
	},
	methods: {
		initForm() {
			// 设置初始值
			Object.entries(this.options).forEach(([key, field]) => {
				if (field.type === 'radio') {
					this.model[key] = '0';
				}
				if (field.type === 'timeRadio') {
					this.model[key] = '0';
				} else if (field.type === 'checkbox') {
					this.model[key] = []; // 多选初始化为空数组
				} else {
					this.model[key] = field.value || ''; // 其他类型初始化为空字符串
				}
				if (field.type === 'subBranchType') {
					this.model[key] = '0';
					this.changeSubBranchType(this.model[key]);
				}
			});
		},
		// 切换支行信息
		changeSubBranchType(index) {
			if (index == '0') {
				this.options.selectP.isShow = 0;
				this.options.slelectC.isShow = 0;
				this.options.affiliatedBranch.isShow = 0;
				this.options.interbankNumber.isShow = 1;
			} else {
				this.options.selectP.isShow = 1;
				this.options.slelectC.isShow = 1;
				this.options.affiliatedBranch.isShow = 1;
				this.options.interbankNumber.isShow = 0;
			}
		},
		// 获取省份
		async getProvinceList() {
			this.areasInfo.areaLevel = 1;
			let res = await areaListApi(this.areasInfo);
			this.provinces = this.formatAreaData(res.data);
		},
		// 获取城市
		async getCityList() {
			this.areasInfo.areaLevel = 2;
			this.areasInfo.parentCityCd = this.model.selectP;
			let res = await areaListApi(this.areasInfo);
			this.citys = this.formatAreaData(res.data);
		},
		// 获取支行
		async getBankList() {
			let data = {
				bankCode: '',
				bankName: this.model.bankBranch,
				bankType: '',
				cityCode: this.model.selectC,
				mainPass: 1
			};
			let res = await bankListApi(data);
			res.data.forEach((item) => {
				item.value = item.bankCode;
				item.text = item.bankName;
			});
			this.bankList = res.data;
		},
		// 处理格式
		formatAreaData(data) {
			return data.map((item) => ({
				...item,
				value: item.cityCd,
				text: item.cityNm
			}));
		},
		// 选中省份
		changeProvinces(value) {
			this.model.selectP = value;
			this.getCityList();
		},
		// 选中城市
		changeCitys(value) {
			this.model.selectC = value;
			this.getBankList();
		},
		// 选择支行
		changeBank(value) {
			this.model.selectAB = value;
		},

		// 打开商户类型
		openMerchantType() {
			this.merchantTypeShow = true;
		},
		closeMerchantType() {
			this.merchantTypeShow = false;
		},
		// 选择商户类型
		merchantTypeHandler(item) {
			this.model.merchantType = item.name;
			this.merchantType = item.name;
			this.closeMerchantType();
		},

		getModel() {
			let model = this.model;
			if (this.$refs.payRate) {
				this.model['rateInfo'] = this.$refs.payRate[0].model; // 多选初始化为空数组
			}
			return toRaw(model);
		},
		validate() {
			this.$refs.form
				.validate()
				.then((res) => {
					uni.showToast({
						icon: 'success',
						title: '校验通过'
					});
					return true;
				})
				.catch((errors) => {
					uni.showToast({
						icon: 'error',
						title: '校验失败'
					});
					return false;
				});
		},
		// 生成验证规则
		generateRules() {
			return Object.fromEntries(
				Object.entries(this.fields)
					.map(([key, field]) => {
						return field.validate
							? [
									`userInfo.${key}`,
									{
										required: field.validate.required,
										message: `${field.title} 是必填项`,
										trigger: ['blur', 'change']
									}
							  ]
							: null;
					})
					.filter(Boolean)
			);
		},
		//弹窗确定事件反馈
		poupCheckConfirm(e) {
			console.log('复选框选中值', e);
		},
		//时间单选切换
		timeChageRadio() {
			console.log('切换');
		},
		//打开地区选择器
		selectArea() {
			this.$refs.areaVue[0].open();
		},
		//打开滚动选择器
		openScollPick() {
			this.$refs.scollPickVue[0].openPicker();
		}
	}
};
</script>

<style scoped lang="scss">
.mar10 {
	margin: 10rpx;
}

::v-deep .uv-form-item__body__left__content__label {
	font-size: 26rpx;
}

.subTitle {
	font-size: 24rpx;
	color: var(--themeDefultFontColor);
	margin: 10rpx 0;
}
</style>
